// 获取DOM元素
const display = document.getElementById('display');
const history = document.getElementById('history');
const buttons = document.querySelectorAll('.btn');

// 计算器状态
let currentValue = '0';
let previousValue = '';
let operator = '';
let resetScreen = false;
let calculationHistory = '';

// 初始化计算器
function initCalculator() {
    buttons.forEach(button => {
        button.addEventListener('click', handleButtonClick);
    });
    
    // 添加键盘支持
    document.addEventListener('keydown', handleKeyPress);
    
    // 添加按钮点击音效
    addButtonSound();
}

// 处理按钮点击
function handleButtonClick(e) {
    const value = e.target.dataset.value;
    processInput(value);
}

// 处理键盘输入
function handleKeyPress(e) {
    // 数字键
    if (e.key >= '0' && e.key <= '9') {
        processInput(e.key);
    }
    // 运算符键
    else if (['+', '-', '*', '/'].includes(e.key)) {
        let op = e.key;
        if (op === '*') op = '×';
        if (op === '/') op = '÷';
        processInput(op);
    }
    // 特殊键
    else if (e.key === '.') processInput('.');
    else if (e.key === '=' || e.key === 'Enter') processInput('=');
    else if (e.key === 'Escape' || e.key === 'c' || e.key === 'C') processInput('clear');
    else if (e.key === 'Backspace') processInput('backspace');
}

// 处理输入
function processInput(value) {
    // 数字输入
    if (value >= '0' && value <= '9') {
        handleNumber(value);
    }
    // 小数点
    else if (value === '.') {
        handleDecimal();
    }
    // 运算符
    else if (['+', '-', '×', '÷'].includes(value)) {
        handleOperator(value);
    }
    // 等号
    else if (value === '=') {
        calculate();
    }
    // 清除
    else if (value === 'clear') {
        clearCalculator();
    }
    // 退格
    else if (value === 'backspace') {
        handleBackspace();
    }
    
    // 更新显示
    updateDisplay();
}

// 处理数字输入
function handleNumber(number) {
    if (resetScreen) {
        currentValue = number;
        resetScreen = false;
    } else {
        // 避免显示前导零
        currentValue = currentValue === '0' ? number : currentValue + number;
    }
    
    // 限制显示长度
    if (currentValue.length > 12) {
        currentValue = currentValue.substring(0, 12);
    }
}

// 处理小数点
function handleDecimal() {
    if (resetScreen) {
        currentValue = '0.';
        resetScreen = false;
    } else if (!currentValue.includes('.')) {
        currentValue += '.';
    }
}

// 处理运算符
function handleOperator(op) {
    // 如果已经有等待计算的操作，先执行计算
    if (operator && previousValue) {
        calculate();
    }
    
    operator = op;
    previousValue = currentValue;
    calculationHistory = `${previousValue} ${operator}`;
    resetScreen = true;
}

// 执行计算
function calculate() {
    if (!operator || previousValue === '' || resetScreen) return;
    
    let result;
    const prev = parseFloat(previousValue);
    const current = parseFloat(currentValue);
    
    // 构建完整的计算表达式
    const fullExpression = `${previousValue} ${operator} ${currentValue} =`;
    
    // 执行计算
    try {
        switch (operator) {
            case '+':
                result = prev + current;
                break;
            case '-':
                result = prev - current;
                break;
            case '×':
                result = prev * current;
                break;
            case '÷':
                if (current === 0) {
                    throw new Error('除数不能为零');
                }
                result = prev / current;
                break;
        }
        
        // 处理结果显示格式
        result = formatResult(result);
        
        // 更新显示和状态
        currentValue = result;
        history.textContent = fullExpression;
        
    } catch (error) {
        // 错误处理
        currentValue = '错误';
        history.textContent = error.message;
    }
    
    // 重置状态
    operator = '';
    previousValue = '';
    resetScreen = true;
}

// 格式化计算结果
function formatResult(result) {
    // 检查是否为无穷大或NaN
    if (!isFinite(result)) {
        return '错误';
    }
    
    // 限制小数位数
    if (Number.isInteger(result)) {
        return result.toString();
    } else {
        // 保留足够的小数位但不超过8位
        const fixed = result.toFixed(8);
        // 移除末尾的零和小数点（如果需要）
        return parseFloat(fixed).toString();
    }
}

// 清除计算器
function clearCalculator() {
    currentValue = '0';
    previousValue = '';
    operator = '';
    calculationHistory = '';
    resetScreen = false;
    history.textContent = '';
}

// 处理退格
function handleBackspace() {
    if (resetScreen) {
        currentValue = '0';
        resetScreen = false;
    } else if (currentValue.length > 1) {
        currentValue = currentValue.slice(0, -1);
    } else {
        currentValue = '0';
    }
}

// 更新显示
function updateDisplay() {
    // 如果显示的是数字，添加千位分隔符（如果需要）
    if (currentValue !== '0' && currentValue !== '错误' && !isNaN(currentValue)) {
        // 分开整数和小数部分
        const parts = currentValue.split('.');
        if (parts[0].length > 3) {
            // 为整数部分添加千位分隔符
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        }
        display.textContent = parts.join('.');
    } else {
        display.textContent = currentValue;
    }
    
    // 更新历史记录显示
    if (calculationHistory && !resetScreen && !['+', '-', '×', '÷'].includes(currentValue)) {
        history.textContent = calculationHistory + ' ' + currentValue;
    }
}

// 添加按钮点击音效
function addButtonSound() {
    // 简单的音效，不使用大量base64数据
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();
    
    buttons.forEach(button => {
        button.addEventListener('click', () => {
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);
            
            // 根据按钮类型设置不同的音调
            if (button.classList.contains('number') || button.classList.contains('decimal')) {
                oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
            } else if (button.classList.contains('operator')) {
                oscillator.frequency.setValueAtTime(600, audioContext.currentTime);
            } else if (button.classList.contains('equals')) {
                oscillator.frequency.setValueAtTime(1000, audioContext.currentTime);
            } else {
                oscillator.frequency.setValueAtTime(400, audioContext.currentTime);
            }
            
            oscillator.type = 'sine';
            gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.05);
            
            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.05);
        });
    });
}

// 页面加载完成后初始化计算器
document.addEventListener('DOMContentLoaded', initCalculator);